<?php

namespace App\Http\Resources\Game\Other\Email\Player;

use App\Http\Resources\Resource;
use App\Http\Resources\Traits\Attributes;
use App\Http\Resources\Traits\Paginate;

class DatasResource extends Resource
{
    use Attributes, Paginate;

    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $this->setAttribute('data', $this->makeDatas(parent::toArray($request)));

        if ($this->isValidPaginate()) {
            $this->setAttribute('meta', $this->getPaginate($request));
        }

        return $this->getResponse()->setResponseData($this->getAttributes());
    }

    /**
     * 制作数据
     *
     * @param $datas
     * @return array
     */
    private function makeDatas($datas)
    {
        foreach ($datas as &$item) {
            foreach ($item['bodys'] as &$body) {
                $body['content_format'] = sprintf($body['content'], ...$item['body_param']);
            }
            $item['body_ids'] = array_column($item['bodys'], 'id');
            $item['title_ids'] = array_column($item['titles'], 'id');
        }
        return $datas;
    }
}
